package com.xhu.water_supply.web.controller;

import com.nimbusds.jose.JOSEException;
import com.xhu.water_supply.constants.Constants;
import com.xhu.water_supply.dto.Result;
import com.xhu.water_supply.dto.ResultUtils;
import com.xhu.water_supply.utils.UUIDUtils;
import com.xhu.water_supply.web.utils.JwtComponent;
import com.xhu.water_supply.web.utils.PayloadDTO;
import com.xhu.water_supply.web.vo.CodeVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Api(tags = "验证码接口")
@RestController
@RequestMapping("api/code")
public class CodeController {
    @Autowired
    private JwtComponent jwtComponent;

    @ApiOperation(value = "获取登录验证码", httpMethod = "GET")
    @RequestMapping("login")
    public Result<CodeVO> getLoginCode() throws JOSEException {
        //验证码下发前，也可以暂时保存在Redis中，以加强安全性
        return this.createCode(Constants.JWT_SECRET_LOGIN);
    }

    @ApiOperation(value = "获取注册证码", httpMethod = "GET")
    @RequestMapping("reg")
    public Result<CodeVO> getRegCode() throws JOSEException {
        return this.createCode(Constants.JWT_SECRET);
    }

    /**
     * 根据传入的秘钥生成验证码视图对象
     * @param secret
     * @return
     */
    private Result<CodeVO> createCode(String secret) throws JOSEException {
        String code = UUIDUtils.getRandomCodeUpper();
        //创建code的负载对象，包含过期时间
        PayloadDTO payload = jwtComponent.getDefaultPayloadDTO(code, null, null);
        //生成验证码的唯一标识
        String token = jwtComponent.generateTokenByHmac(payload, secret);
        //下发结果
        CodeVO codeVO = CodeVO.builder()
                .code(code)
                .codeUid(token)
                .build();
        return ResultUtils.returnDataSuccess(codeVO);
    }

}
